package wiki.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 
 * @author <p><strong>JwTeam</strong></p> 
 *
 */
import wiki.generic.contents.Content;
import wiki.generic.io.Element;
import wiki.generic.utilities.PageNotFoundException;
import wiki.setup.Setup;
/**
 * 
 * @author <p><strong>JwTeam</strong></p> 
 * Responsabile della ricerca di testo nelle pagine
 */
public class WikiSearchServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession ses=req.getSession(false);
		if(ses!=null){
			long t1=System.nanoTime();
			String corso=(String) ses.getAttribute("corso");
			HashMap<String, String> map=Setup.getSetup().getMediator().getpService().getPagesMap(corso);
			Set<String> keys=map.keySet();
			HashMap<String, List<Content>> cmap=new HashMap<String, List<Content>>();
			for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
				String pname= iterator.next();
				try {
					cmap.put(pname, Setup.getSetup().getMediator().getpService().getCurrentPageContents(corso, pname));
				} catch (PageNotFoundException e) {
					resp.sendRedirect("./html/errorpages/pagina404.html");
					return;
				}
			}
			
			String key=req.getParameter("key");
			key=Setup.getSetup().getMediator().getGpService().changeHTMLText(key);
			String lowerKey=key.toLowerCase();
			
			String[] vet={"h3","p"};
			Set<String> pages=cmap.keySet();
			List<HashMap<Integer, List<String>>> fmaps=new ArrayList<HashMap<Integer,List<String>>>(); 
			for (int i = 0; i < vet.length; i++) {
				String type=vet[i];
				HashMap<Integer, Element> elmap=Setup.getSetup().getMediator().getVservice().getElementsMapbyType(type);
				Set<Integer> ids=elmap.keySet();
				List<Integer> list=new ArrayList<Integer>();
				for (Iterator<Integer> iterator = ids.iterator(); iterator.hasNext();) {
					Integer ID =iterator.next();
					String testo=elmap.get(ID).getInfo();
					String lowerTesto=testo.toLowerCase();
					if(lowerTesto.contains(lowerKey)){
						list.add(ID);
					}
				}
				HashMap<Integer, List<String>> imap=new HashMap<Integer, List<String>>();
				for (int j = 0; j < list.size(); j++) {
					int ID=list.get(j);
					List<String> related=new ArrayList<String>();
					for (Iterator<String> iterator = pages.iterator(); iterator
							.hasNext();) {
						String p = iterator.next();
						List<Content> cont=cmap.get(p);
						for (int k = 0; k < cont.size(); k++) {
							Content buf=cont.get(k);
							if(buf.getType().equals(vet[i]) && buf.getID()==ID){
								related.add(p);
							}
						}
					}
					if(related.size()>0){
						imap.put(ID, related);
					}
				}
				fmaps.add(imap);
			}
			
			long t2=System.nanoTime();	
			float time=0.001f*0.001f*(t2-t1);
			
			PrintWriter out=resp.getWriter();
			out.write("<html>\n");
			out.write("<head>\n");
			out.write("<title>Risultati della ricerca</title>\n");
			out.write("<link rel='stylesheet' type='text/css' href='./html/ricerca/ricerca.css'/>");
			out.write("</head>\n");
			out.write("<body>\n");
			out.write("<div id='title'>\n");
			out.write("Risultati della ricerca\n");
			out.write("</div>\n");
			out.write("<div id='container'>\n");
			int resultsNumber=0;
			for (int i = 0; i < fmaps.size(); i++) {
				resultsNumber+=fmaps.get(i).size();
			}
			if(resultsNumber==0){
				resp.sendRedirect("./html/ricerca/norisultati.html");
				return;
			}
			out.write("<h3>La ricerca di <em>"+key+"</em> ha prodotto "+resultsNumber+" risultati</br>&nbsp;&nbsp;&nbsp; in <em>"+time+"</em> ms </h3>\n");
			out.write("<ul>\n");
			
			for (int i = 0; i < fmaps.size(); i++) {
				HashMap<Integer , List<String>> titles=fmaps.get(i);
				Set<Integer> tids=titles.keySet();
				for (Iterator<Integer> iterator = tids.iterator(); iterator.hasNext();) {
					Integer id =iterator.next();
					List<String> pa=titles.get(id);
					String type=vet[i];
					String s=Setup.getSetup().getMediator().getVservice().getContentMainParameterbyID(type, id).getInfo();
					s=Setup.getSetup().getMediator().getGpService().changeHTMLText(s);
					String low=s.toLowerCase();
					List<Integer> occurrances=new ArrayList<Integer>();
					int index=low.indexOf(lowerKey);
					while(index>-1){
					occurrances.add(index);
					low=low.substring(index+lowerKey.length());
					index=low.indexOf(lowerKey);
					}
					String o="";
					for (int l = 0; l < occurrances.size(); l++) {
						int ind=occurrances.get(l);
						String sub1="";
						if(ind!=0){
							sub1=s.substring(0, ind);
						}
						String sub2=s.substring(ind, ind+key.length());
						s=s.substring(ind+key.length());
						o+=sub1+"<span class='marker'>"+sub2+"</span>";
						if(l==occurrances.size()-1){
							o+=s;
						}
					}
				
					if(type.equals("h3")){
						out.write("<li class='par'><img class='lefttitolo' src='./html/immagini/mark3.png' /> &nbsp;&nbsp;<span class='tit'>"+o);		
						out.write("</span></li>\n");
					}
					if(type.equals("p")){
						out.write("<li class='par'><img class='left' src='./html/immagini/Virgolette3.png'/> &nbsp;&nbsp; &nbsp;"+
								o+"</li>" +
										"<img class='right' src='./html/immagini/Virgolette32.png'/>\n");
					}
					for (int j = 0; j < pa.size(); j++) {
							out.write("<li class='page'><a href='./view?page="+pa.get(j)+"'>"+pa.get(j)+"</a></li>\n");
						}
						out.write("<hr>\n");
					
				}
			}
			out.write("</ul>\n");
			out.write("<input type='button' id='bottone' value='Indietro' onclick='history.go(-1);return true;'/>\n");
			out.write("</div>\n");
			out.write("</body>\n");
			out.write("</html>\n");

					} else {
			resp.sendRedirect("./html/LOGIN/login.html");
		}
	}
	
	
}
